package cn.lopr.im.android.receiver;

import android.app.ActivityManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import java.util.List;

import cn.lopr.im.android.R;
import cn.lopr.im.android.db.entity.Message;
import cn.lopr.im.android.mvp.view.activities.MainActivity;

import static cn.lopr.im.android.common.Constant.NOTIFICATION_ID;

public class NotificationReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (!isForeground(context) && intent.getAction().equals("cn.lopr.im.android.servicecallback.content")) {
            Message message = (Message) intent.getSerializableExtra("message");

            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                    new Intent(context, MainActivity.class), 0);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_ID)
                    .setSmallIcon(R.drawable.ic_main)
                    .setContentTitle(message.getFromUser())
                    .setContentText(message.getMsg())
                    .setStyle(new NotificationCompat.BigTextStyle().bigText(""))
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true);

            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
            notificationManager.notify(10086, builder.build());

        }
    }

    private boolean isForeground(Context context) {
        if (context != null) {
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> processes = activityManager.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : processes) {
                if (processInfo.processName.equals(context.getPackageName())) {
                    if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
